/**
 * 
 * Copyright (C) 2015 by Elcom Software Company
 *
 * @id: JobManager.java, Mar 13, 2015
 *
 */
package com.nip.commons.job;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.nip.commons.job.objects.JobTime;

/**
 * @author ThangNM<thangnm@elcom.com.vn>
 * 
 * @version v
 */
public class JobManager {

    private final Map<Long, JobCmd> listJob = new HashMap<Long, JobCmd>();
    private long index = 1000;
    private static final JobManager instance = new JobManager();
    private ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    private final JobTime jobTime = new JobTime();
    private final Runnable runnable = new Runnable() {
        
        @Override
        public void run() {
            getInstance().notifyTime();
            
        }
    };
    
    
    public JobManager() {
        Calendar calNow = Calendar.getInstance();
        calNow.setTime(new Date());
        
        Calendar calStart = Calendar.getInstance();
        calStart.set(Calendar.YEAR, calNow.get(Calendar.YEAR));
        calStart.set(Calendar.MONTH, calNow.get(Calendar.MONTH));
        calStart.set(Calendar.DAY_OF_MONTH, calNow.get(Calendar.DAY_OF_MONTH));
        calStart.set(Calendar.HOUR_OF_DAY, calNow.get(Calendar.HOUR_OF_DAY));
        calStart.set(Calendar.MINUTE, calNow.get(Calendar.MINUTE) + 1);
        calStart.set(Calendar.SECOND, 0);
        
        service.scheduleWithFixedDelay(runnable, calStart.getTimeInMillis() - calNow.getTimeInMillis(), 1000*60, TimeUnit.MILLISECONDS);
    }

    /**
     * 
     */
    protected void notifyTime() {
        
        jobTime.setTime(new Date());
        for(long i : listJob.keySet())
        {
            listJob.get(i).notify(jobTime);
        }
        
    }

    public static JobManager getInstance()
    {
        return instance;
    }

    public synchronized long addJob(JobCmd job) {
        listJob.put(index, job);
        return index++;

    }

    public synchronized void removeJob(int jobIndex) {
        listJob.remove(jobIndex);
    }
}
